﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WPFByCoreApp
{
    /// <summary>
    /// TestKeybdEventView.xaml 的交互逻辑
    /// </summary>
    public partial class TestKeybdEventWindow : Window
    {
        public TestKeybdEventWindow()
        {
            InitializeComponent();

            DataObject.AddPastingHandler(tb1, OnPaste);


            Task.Run((Action)delegate
            {
                while (true)
                {
                    keybd_event((int)Keys.LMenu, 0, 0, 0);
                    Thread.Sleep(1000);
                    keybd_event((int)Keys.LMenu, 0, 0x02, 0);
                    Thread.Sleep(1000);
                }
            });
        }

        private void tb1_KeyDown(object sender, KeyEventArgs e)
        {
            Debug.WriteLine("tb1_KeyDown：" + e.Key);
            //Debug.WriteLine("IsKeyDown：" + (Keyboard.IsKeyDown(e.Key)));
            //Debug.WriteLine("IsKeyDown：" + (Keyboard.IsKeyDown(e.Key)));

            tb1.Text = e.Key.ToString();

        }

        private void tb1_KeyUp(object sender, KeyEventArgs e)
        {

        }


        [DllImport("User32.dll")]
        public static extern void keybd_event(byte bVK, byte bScan, Int32 dwFlags, int dwExtraInfo);

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            tb1.Focus();

            //Task.Run((Action)delegate
            //{
            //int num = 0;
            //while (num < 10)
            //{
            if ((System.Windows.Input.Keyboard.Modifiers == System.Windows.Input.ModifierKeys.Alt))
            {
                keybd_event((int)Keys.LMenu, 0, 0x02, 0);
                keybd_event((int)Keys.RMenu, 0, 0x02, 0);
                //        break;

            }
            //    num++;
            //    Thread.Sleep(10);
            //}
            //});


            keybd_event((int)Keys.Enter, 0, 0, 0);
            keybd_event((int)Keys.Enter, 0, 0x02, 0);

            //tb1.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(tb1), 0, Key.OemMinus) { RoutedEvent = Keyboard.KeyDownEvent });
            //tb1.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(tb1), 0, Key.OemMinus) { RoutedEvent = Keyboard.KeyUpEvent });
        }

        private void OnPaste(object sender, DataObjectPastingEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb != null)
            {

            }
        }
    }
}
